#define _CRT_SECURE_NO_WARNINGS 1
#include <stdio.h>
#include <stdlib.h>

typedef struct ListNode
{
    int val;
    struct ListNode* next;
}ListNode;

void SListPrint(ListNode* plist)
{
    ListNode* cur = plist;
    while (cur)
    {
        printf("%d->", cur->val);
        cur = cur->next;
    }
    printf("NULL\n");
}

struct ListNode* mergeTwoLists(struct ListNode* list1, struct ListNode* list2) {
    if (list1 == NULL)
        return list2;
    if (list2 == NULL)
        return list1;

    struct ListNode* phead = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* cur = phead;
    while (list1 && list2)
    {
        if (list1->val < list2->val)
        {
            cur->next = list1;
            list1 = list1->next;
        }
        else
        {
            cur->next = list2;
            list2 = list2->next;
        }
        cur = cur->next;
    }
    if (list1)
        cur->next = list1;
    if (list2)
        cur->next = list2;
    return phead->next;
}

int main()
{
    struct ListNode* n1 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n2 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n3 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n4 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n5 = (struct ListNode*)malloc(sizeof(struct ListNode));
    struct ListNode* n6 = (struct ListNode*)malloc(sizeof(struct ListNode));

    if (n1 == NULL || n2 == NULL || n3 == NULL || n4 == NULL || n5 == NULL || n6 == NULL)
    {
        perror("malloc");
        return -1;
    }

    struct ListNode* head = n1;

    n1->val = 1;
    n2->val = 2;
    n3->val = 4;
    n4->val = 1;
    n5->val = 3;
    n6->val = 4;

    n1->next = n2;
    n2->next = n3;
    n3->next = NULL;
    n4->next = n5;
    n5->next = n6;
    n6->next = NULL;

    SListPrint(n1);
    SListPrint(n4);
    struct ListNode* ret = mergeTwoLists(n1, n4);
    SListPrint(ret);

    return 0;
}